package com.onlyxiahui.common.data.common.value;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import com.alibaba.fastjson.TypeReference;
import com.onlyxiahui.common.message.AbstractMessage;
import com.onlyxiahui.common.message.bean.Info;

/**
 * 
 * 
 * 信息<br>
 * Date 2020-01-14 09:08:57<br>
 * 
 * @author XiaHui [onlovexiahui@qq.com]<br>
 * @param <B> 主体
 * @since 1.0.0
 */
public class MessageValue<B> extends AbstractMessage<B> {

	/**
	 * 消息头部
	 */
	private HeadValue head;
	/**
	 * 消息主体
	 */
	private B body;
	/**
	 * 消息响应信息（成功/异常）
	 */
	private Info info = new Info();
	private String json = null;

	public HeadValue getHead() {
		return head;
	}

	public void setHead(HeadValue head) {
		this.head = head;
	}

	public B getBody() {
		return body;
	}

	public void setBody(B body) {
		this.body = body;
	}

	public Info getInfo() {
		return info;
	}

	public void setInfo(Info info) {
		this.info = info;
	}

	public boolean isSuccess() {
		return null != info && info.isSuccess();
	}

	public void addError(String code, String text) {
		if (null == info) {
			info = new Info();
		}
		info.addError(code, text);
	}

	public void addWarning(String code, String text) {
		if (null == info) {
			info = new Info();
		}
		info.addWarning(code, text);
	}

	public void addPrompt(String code, String text) {
		if (null == info) {
			info = new Info();
		}
		info.addPrompt(code, text);
	}

	public void setJsonData(String json) {
		this.json = json;
	}

	@SuppressWarnings("unchecked")
	public <T> T get(String path, TypeReference<T> type) {
		T object = null;
		if (JSONObject.isValid(json) && null != type) {
			Object value = null;
			if (null == path || "".equals(path)) {
				value = JSONObject.parseObject(json, type);
			} else {
				value = JSONPath.read(json, path);
			}
			if (value instanceof JSONObject) {
				JSONObject jo = (JSONObject) value;
				object = jo.toJavaObject(type);
			} else if (value instanceof JSONArray) {
				JSONArray ja = (JSONArray) value;
				object = ja.toJavaObject(type);
			} else if (null != value) {
				if (value.getClass().equals(type.getType())) {
					object = (T) value;
				}
			}
		}
		return object;
	}

	@SuppressWarnings("unchecked")
	public <T> T get(String path, Class<T> clazz) {
		T object = null;
		if (JSONObject.isValid(json) && null != clazz) {
			Object value = null;
			if (null == path || "".equals(path)) {
				value = JSONObject.parseObject(json, clazz);
			} else {
				value = JSONPath.read(json, path);
			}

			if (value instanceof JSONObject) {
				JSONObject jo = (JSONObject) value;
				object = jo.toJavaObject(clazz);
			} else if (value instanceof JSONArray) {
				JSONArray ja = (JSONArray) value;
				object = ja.toJavaObject(clazz);
			} else if (null != value) {
				if (clazz.isInstance(value)) {
					object = (T) value;
				}
			}
		}
		return object;
	}
}
